import jsPDF from "jspdf";
import html2canvas from "html2canvas";
// http://www.rotisedapsales.com/snr/cloud2/website/jsPDF-master/docs/jsPDF.html
// https://gitee.com/jseven68/vue-pdf2 算法参考地址

import {Message} from "element-ui";
import {PdfLoader} from "@/utils/pdfPro/pdfLoader";


/**
 * 生成pdf
 * @param {number} param.sliceHeight - 分页高度
 *
 *
 * */


export class customPdfLoader {
  constructor(element, param = {}) {
    if (!(element instanceof HTMLElement)) {
      throw new TypeError("element节点请传入dom节点");
    }

    // jsPDF实例
    const pdf = new jsPDF({
      unit: "pt", // mm,pt,in,cm
      format: "a4",
      orientation: 'p',
    });
    this.pdf = pdf

    this.A4_WIDTH = 595; // a4纸的尺寸[595,842],单位像素
    this.A4_HEIGHT = 842;

    this.zoom=595/1000


    //获取要转换的pdf节点
    this.element = element;
    //html高度
    this.boxHeight = element.style.height.split('px')[0]

    console.log(this.boxHeight, 'html')




    this.contentHeight = param.sliceHeight || 800;
    this.pageList = [];
    this.pageData = []
    // 将html转换成画布



  }


  async toCanvas(element, width) {

    let Page = Math.ceil(this.boxHeight / this.contentHeight)
    console.log(Page, 'Page')

    for (let i = 0; i < Page; i++) {
      this.pdf.addPage();
      let canvas = await html2canvas(element, {
        width: width || 800,
        height: this.contentHeight,
        scale: 2,
        useCORS: true,
        logging: false,
        allowTaint: true,
        dpi: 300,
        backgroundColor: '#fff',
        removeContainer: true,
        y: i * this.contentHeight,
        x: 0
      })
      // this.pageList.push(canvas)
      canvas.style.borderBottom = '1px solid green'
      this.pageData.push(this.toDataUrl(canvas))
      this.pdf.addImage(this.toDataUrl(canvas), "JPEG", 0, 0, 595, 842);
      Message.success(`共${Page}页,生成第${i + 1}页`);
      canvas=null
    }
    console.log(this.pageList, 'this.pageList', this.pageData)
    this.pdf.save('test.pdf')


  }


  toDataUrl(canvas) {
    return canvas.toDataURL('image/jpeg', 1.0)
  }


  getPdf() {

    return new Promise(async (resolve, reject) => {


    await  this.toCanvas(this.element, 1000)
      resolve('导出完成')
    })



  }
}
